import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Cate from '@/views/layout/cate'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/',
      redirect: '/home',
      component: Layout,
      children: [
        // 二级路由：在children配规则，直接写/二级路由名字
        {
          path: '/home',
          component: Home
        },
        {
          path: '/cate',
          component: Cate
        },
        {
          path: '/cart',
          component: Cart
        },
        {
          path: '/user',
          component: User
        }
      ]
    },
    {
      path: '/search',
      component: () => import('@/views/search')
    },
    {
      path: '/searchlist',
      component: () => import('@/views/search/list')
    },
    {
      path: '/prodetail/:id',
      component: () => import('@/views/prodetail')
    },
    {
      path: '/pay',
      component: () => import('@/views/pay')
    },
    {
      path: '/myorder',
      component: () => import('@/views/myorder')
    }
  ]
})

// 定义一个数组，专门存放用户所有需要权限访问的页面
const authUrls = ['/pay', '/myorder']
// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  // to:到哪去，到哪去的完整路由对象（路径，参数）
  // from:从哪来，从到哪来的完整路由对象（路径，参数）
  // next()：是否放行，next()不带任何参数就是放行；next(路径)是进行拦截，拦截到next里面配置的路径
  // to form 是两个对象  next是一个函数
  // 所有的路由在真正被访问之前，都会先经过全局前置路由守卫，
  // 只有全局前置守卫放行了，才会到达对应的页面
  // 返回 false 以取消导
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行
    next()
    return
  }
  // 能走到这里，说明是权限页面，需要判断token
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
  return false
})
export default router
